package com.example.onlineeducation.ui.offline

import android.content.Context
import android.content.Intent
import android.text.Editable
import android.view.KeyEvent
import android.view.inputmethod.EditorInfo
import android.widget.TextView
import androidx.activity.result.ActivityResultLauncher
import com.example.onlineeducation.App
import com.example.onlineeducation.R
import com.example.onlineeducation.base.BaseActivity
import com.example.onlineeducation.data.constant.ExamConstants
import com.example.onlineeducation.data.entity.OfflineExamDetailEntity
import com.example.onlineeducation.data.entity.OfflineExamDetailTranEntity
import com.example.onlineeducation.data.model.OfflineExamRecordDataModel
import com.example.onlineeducation.databinding.OfflineExamRecordSearchActivityBinding
import com.example.onlineeducation.databinding.OfflineExamRecordListItemBinding
import com.example.onlineeducation.viewmodel.OfflineExamRecordListVM
import com.yc.jetpacklib.extension.showToast
import com.yc.jetpacklib.extension.ycInitLinearLayoutManage
import com.yc.jetpacklib.extension.ycIsNotEmpty
import com.yc.jetpacklib.extension.ycLoadImageNetCircle
import com.yc.jetpacklib.recycleView.YcPagingDataAdapter
import com.yc.jetpacklib.refresh.YcRefreshBaseUtil
import com.yc.jetpacklib.refresh.YcRefreshSpecialPagingUtil
import com.yc.jetpacklib.utils.YcResources
import com.yc.jetpacklib.widget.YcTextWatcher

/**
 * Creator:
 * Date: 2022/4/1 15:10
 * UseDes:线下考试记录搜索
 */
class OfflineExamRecordSearchActivity : BaseActivity<OfflineExamRecordSearchActivityBinding>(OfflineExamRecordSearchActivityBinding::inflate) {
    private val mViewModel by ycViewModels<OfflineExamRecordListVM>()
    private var mProId: String? = null
    private var mExamId: String? = null
    private var mStartTime: String? = null
    private var mEndTime: String? = null
    private var mTotalScore: String = "0"
    private lateinit var mRefreshUtil: YcRefreshBaseUtil<OfflineExamRecordDataModel>
    private lateinit var detailLauncher: ActivityResultLauncher<Intent>

    companion object {
        private const val KEY_EXAM_ID = "key_exam_id"
        private const val KEY_START_TIME = "key_start_time"
        private const val KEY_END_TIME = "key_end_time"
        private const val KEY_TOTAL_SCORE = "key_total_score"

        @JvmStatic
        fun newInstance(context: Context, id: String?, startTime: String?, endTime: String?, totalScore: String) {
            val intent = Intent(context, OfflineExamRecordSearchActivity::class.java).apply {
                putExtra(KEY_EXAM_ID, id)
                putExtra(KEY_START_TIME, startTime)
                putExtra(KEY_END_TIME, endTime)
                putExtra(KEY_TOTAL_SCORE, totalScore)
            }
            context.startActivity(intent)
        }
    }

    private val mAdapter: YcPagingDataAdapter<OfflineExamRecordDataModel, OfflineExamRecordListItemBinding>
            by YcPagingDataAdapter.ycLazyInitApply(OfflineExamRecordListItemBinding::inflate, OfflineExamRecordDataModel.diffCallback) {
                mOnUpdate = {
                    ivAvatar.ycLoadImageNetCircle(it.avatar, R.drawable.ic_avatar2, R.drawable.ic_avatar2)
                    tvName.text = it.userName
                    tvWorkType.text = it.workType
                    tvState.text = ExamConstants.showResultText(it.state)
                    if (it.state == ExamConstants.UN_PASSED) {
                        tvState.background = YcResources.getDrawable(R.drawable.shape_round_exam_label_unpass)
                    } else {
                        tvState.background = YcResources.getDrawable(R.drawable.shape_round_exam_label_pass)
                    }
                    tvExamScores.text = it.examScores
                    tvAnswerTime.text = it.answerTime.toString()
                    tvExamDate.text = it.examDate
                }
                mItemClick = {
                    if (it.id.ycIsNotEmpty()) {
                        OfflineExamDetailActivity.newInstance(
                            this@OfflineExamRecordSearchActivity,
                            OfflineExamDetailTranEntity(
                                it.id!!, it.userName, it.workType, it.examScores, it.answerTime, it.examDate,
                                it.groupName, it.webPathList, mStartTime, mEndTime, mTotalScore
                            ), detailLauncher
                        )
                    } else {
                        showToast("考试记录Id无效,请联系管理员")
                    }
                }
            }

    override fun OfflineExamRecordSearchActivityBinding.initView() {
        intent.apply {
            mExamId = getStringExtra(KEY_EXAM_ID)!!
            mStartTime = getStringExtra(KEY_START_TIME)
            mEndTime = getStringExtra(KEY_END_TIME)
            mTotalScore = getStringExtra(KEY_TOTAL_SCORE) ?: "0"
        }

        detailLauncher = OfflineExamDetailActivity.getLauncher(this@OfflineExamRecordSearchActivity) {
            mRefreshUtil.startRefresh()
        }
        etSearch.apply {
            hint = "请输入人员姓名"
            addTextChangedListener(object : YcTextWatcher() {
                override fun afterTextChanged(s: Editable?) {
                    getData()
                }
            })
            setOnEditorActionListener(TextView.OnEditorActionListener { _: TextView?, actionId: Int, _: KeyEvent? ->
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    mRefreshUtil.startRefresh(true)
                    return@OnEditorActionListener true
                }
                false
            })
            tvCancel.setOnClickListener { finish() }
        }
        rv.apply {
            adapter = mAdapter
            ycInitLinearLayoutManage()
        }
        mRefreshUtil = YcRefreshSpecialPagingUtil<OfflineExamRecordDataModel>(this@OfflineExamRecordSearchActivity)
            .build(mAdapter, srl, rv, fl) {
                mRefreshCall = {
                    getData()
                }
            }
        mRefreshUtil.startRefresh()
        App.mInstant.mViewModel.mProInfoEntity.observe {
            mProId = it!!.proId
        }
        mViewModel.mOfflineExamRecordList.observe {
            mRefreshUtil.acSetPagingData(it)
        }
    }

    private fun OfflineExamRecordSearchActivityBinding.getData() {
        mViewModel.getOfflineExamRecordListPager(mProId!!, mExamId!!, etSearch.text.toString())
    }
}